import json

import numpy as np
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from apps.api.Model.train import predict
from apps.api.mapper.sql_connect import verify_user_login, register_user, del_bike_data, del_user_data, modify_user_data


# 登录逻辑
@csrf_exempt
def login(request):
    form = json.loads(request.body)
    if form:
        # 登录校验
        result = verify_user_login(form['username'], form['password'])
        if result:
            code = 1
            message = "登录成功。"

        else:
            code = 0
            message = "登录失败，出现错误。"
    else:
        # 没有接收到数据
        code = 0
        message = "没有接收到数据"
    response = {
        'code': code,
        'message': message
    }
    return JsonResponse(response)


# 注册逻辑
@csrf_exempt
def register(request):
    form = json.loads(request.body)
    if form:
        # 登录校验
        result = register_user(form['username'], form['password'])
        if result:
            code = 1
            message = "注册成功。"

        else:
            code = 0
            message = "注册失败，用户名已经存在"
    else:
        # 没有接收到数据
        code = 0
        message = "没有接收到数据"
    response = {
        'code': code,
        'message': message
    }
    return JsonResponse(response)


# 自行车自聘数量预测接口
@csrf_exempt
def rent_predict(request):
    if request.method == 'POST':
        # 获取 FormData 数据
        hour = float(request.POST.get('hour'))
        temperature = float(request.POST.get('temperature'))
        humidity = float(request.POST.get('humidity'))
        windspeed = float(request.POST.get('windspeed'))
        visibility = float(request.POST.get('visibility'))
        dewpoint = float(request.POST.get('dewpoint'))
        solar = float(request.POST.get('solar'))
        rainfall = float(request.POST.get('rainfall'))
        snowfall = float(request.POST.get('snowfall'))
        data = np.array([[hour, temperature, humidity, windspeed, visibility, dewpoint, solar, rainfall, snowfall]])
        pred = predict(data)
        response = {
            'code': 1,
            'message': "success",
            'data': pred
        }
        return JsonResponse(response)


# 修改车辆数据
@csrf_exempt
def modify_bike(request):
    if request.method == "POST":
        try:
            # 从POST请求中获取表单数据
            date = request.POST.get('date')
            if date == None:
                raise ValueError
            rented_bike_count = request.POST.get('RentedBikeCount')
            hour = request.POST.get('Hour')
            temperature = request.POST.get('Temperature')
            humidity = request.POST.get('Humidity')
            wind_speed = request.POST.get('WindSpeed')
            visibility = request.POST.get('Visibility')
            dew_point_temperature = request.POST.get('DewPointTemperature')
            solar_radiation = request.POST.get('SolarRadiation')
            rainfall = request.POST.get('Rainfall')
            snowfall = request.POST.get('Snowfall')
            seasons = request.POST.get('Seasons')
            holiday = request.POST.get('Holiday')
            functioning_day = request.POST.get('FunctioningDay')
            response = {
                'code': 1,
                "message": "success",
                "data": "修改成功"
            }
            return JsonResponse(response)
        except Exception as e:
            response = {
                'code': 0,
                "message": "fail",
                "data": "修改失败，请确认您输入的数据是完整的。"
            }
            return JsonResponse(response)


# 删除自行车数据
@csrf_exempt
def del_bike(request):
    bike_count = json.loads(request.body)['RentedBikeCount']
    print(bike_count)
    result = del_bike_data(bike_count)
    if result:
        response = {
            'code': 1,
            'message': "success",
            'data': "删除成功，请刷新页面重新获取数据。"
        }
        return JsonResponse(response)


# 删除用户
@csrf_exempt
def del_user(request):
    username = json.loads(request.body)['username']
    result = del_user_data(username)
    if result:
        response = {
            'code': 1,
            'message': "success",
            "data": f"删除用户{username}成功，请刷新页面查看"
        }
        return JsonResponse(response)


# 修改用户信息
@csrf_exempt
def modify_user(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    status = request.POST.get('status')
    result = modify_user_data(username, password, status)
    if result:
        response = {
            'code': 1,
            "message": "success",
            "data": "修改成功，请刷新页面查看数据。"
        }
        return JsonResponse(response)
